package com.bscc.admin.file;

import com.alibaba.fastjson.JSONObject;
import com.bscc.common.utils.Base64Utils;
import com.bscc.common.utils.CommonUtils;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.upload.UploadFile;

import java.io.*;

public class FileUploadController extends Controller
{
    public void imageUpload()
    {
        String fileUploadPath =  PropKit.get("fileUploadPath");
        String fileAccessPath = PropKit.get("fileAccessPath");

        String reSavePath = "/images/" + CommonUtils.getCurrentDate();

        fileUploadPath += reSavePath;
        String fileSaveName = CommonUtils.getCurrentTime()+"_"+CommonUtils.getUUID();

        String reAccessPath;
        UploadFile uploadFile = this.getFile("image", reSavePath, 20 * 1024 * 1024, "utf-8");
        fileSaveName += uploadFile.getFileName().substring(uploadFile.getFileName().lastIndexOf("."));
        boolean renameSuccess = uploadFile.getFile().renameTo(new File(fileUploadPath+"/"+fileSaveName));
        if(renameSuccess)
            reAccessPath = reSavePath+"/"+fileSaveName;
        else
            reAccessPath = reSavePath+"/"+uploadFile.getFileName();

        JSONObject json = new JSONObject();

        json.put("error", 0);
        json.put("url", reAccessPath);
        json.put("path", fileAccessPath);

        renderJson(json.toJSONString());
    }


    public void imageUploadBase64()
    {
        String fileUploadPath =  PropKit.get("fileUploadPath");
        String fileAccessPath = PropKit.get("fileAccessPath");

        String param = getPara("image");
        String ext = param.substring(param.indexOf("/")+1,param.indexOf(";"));
        String base64Data = param.substring(param.indexOf(",")+1);
        System.out.println(param);
        String reSavePath = "/images/" + CommonUtils.getCurrentDate();

        fileUploadPath += reSavePath;
        File saveDir = new File(fileUploadPath);
        if(!saveDir.exists() || !saveDir.isDirectory())
            saveDir.mkdirs();

        String fileSaveName = CommonUtils.getCurrentTime()+"_"+CommonUtils.getUUID()+"."+ext;
        boolean result= Base64Utils.generateImage(base64Data, fileUploadPath+"/"+fileSaveName);
        JSONObject json = new JSONObject();
        if(result)
        {
            json.put("error", 0);
            json.put("url", reSavePath+"/"+fileSaveName);
            json.put("path", fileAccessPath);
        }
        else
        {
            json.put("error", -1);
            json.put("msg", "图片上传失败");
        }

        renderJson(json.toJSONString());
    }
}
